Function Parameters in C++

Posted on December 14, 2023 by Vishesh Namdev
Python C C++ Java
...

Function parameter in C++ like an ingredient you give to a recipe (the function). The recipe specifies what kind of ingredients it needs (parameter types), and when you cook (call) the recipe, you provide the actual ingredients (arguments). The function then uses these ingredients to perform its task and might give you a tasty result. Parameters help functions customize their actions based on what you give them.

Syntax of a Function Paramters:

ReturnType functionName(ParameterType1 paramName1, ParameterType2 paramName2, ...) {
    // Function body
    // Use paramName1, paramName2, etc., to perform operations
    // Optionally, return a value of ReturnType
}

Functions can be categorized into two main types based on parameters, functions with parameters and functions without parameters.

Functions with Parameters

Functions with parameters receive input values, known as parameters, when they are called. These parameters allow the function to perform operations or computations using the provided values.

// Include necessary header
#include <iostream>

// Function with parameters
void greetUser(std::string name) {
    std::cout << "Hello, " << name << "!" << std::endl;
}

// Main function
int main() {
    // Calling the function with a parameter
    greetUser("John");

    return 0;
}

In this example, the greetUser function takes a single parameter name, allowing it to greet the user by name when called.

Functions without Parameters

Functions without parameters do not take any input values when they are called. They are designed to perform a task or provide a result without relying on external values.

// Include necessary header
#include <iostream>

// Function without parameters
void printMessage() {
    std::cout << "This is a simple message." << std::endl;
}

// Main function
int main() {
    // Calling the function without parameters
    printMessage();

    return 0;
}

In this example, the printMessage function does not require any input parameters. It simply prints a predefined message when called.